import {
	config
} from "../config/config";
import {
	autoLogin,
	clearLoginState,
	promisic
} from "./util";
import {
	WxUtil
} from "./wxutil";
class Http {
	static async request({
		url,
		data,
		method = 'POST',
		baseUrl = '',
		showLoading = true,
		header = {
			Authorization:'Bearer '+(uni.getStorageSync('token') || '')
		}
	}, redirect = true, showToast = true, msg = '') {
		return new Promise(async (resolve, reject) => {
			if(showLoading){
				uni.showLoading({
					title:'加载中'
				})
			}
			Http._doRequest(url, data, method, baseUrl, header).then((res) => {
				if (res.data.code == 200) {
					uni.hideLoading()
					resolve(res.data)
				} else if (res.data.code == 401) {
					// autoLogin()
					uni.showToast({
						title: '登录已经过期，请重新登录!',
						icon: 'none'
					})
					clearLoginState()
					uni.hideLoading()
					uni.navigateTo({
						url:'/pages/login/login'
					})
					reject()
				} else {
					console.log("res==!!222==");
					Http.handle400(res, showToast, msg);
					uni.hideLoading()
					reject()
				}
			})
		})

	}

	static async _doRequest(url, data, method = 'POST', baseUrl, header = {}) {
		return await promisic(wx.request)({
			url: baseUrl ? baseUrl : `${config.apiBaseUrl}${url}`,
			data,
			method,
			header
		});
	}

	static handle401(redirect) {
		WxUtil.logout();
		if (redirect) {
			wx.navigateBack({
				delta: 10,
				success: function() {
					wx.switchTab({
						url: '/pages/self/self',
						success: function() {
							WxUtil.showToast('请先登录');
						}
					});
				}
			});
		}
		throw 'Login Required'
	}

	static handle400(res, showToast, msg = '') {
		if (showToast) {
			if (msg) {
				WxUtil.showToast(msg)
			} else {
				WxUtil.showToast(res.data.msg ? res.data.msg : '请求失败');
			}
		}
		throw 'Internal Server Error'
	}
}

export {
	Http
}